<?php

namespace app\manage\controller;

use think\Db;
use think\Log;
use app\common\controller\BaiduService;
use app\common\controller\TengxunService;
use app\common\controller\JuliangService;

/**
 * 广告账户
 */
class Account extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        // 查询条件start
        $channel_id = input('channel_id',0);
        $acc_name = input('acc_name','');
        $adv_id = input('adv_id','');
        $youhua_name = input('youhua_name','');
        $admin_id = input('admin_id',0);
        $map = [];
        if($channel_id != 0){
            $map['channel_id'] = $channel_id;
        }
        if($admin_id != 0){
            $map['admin_id'] = $admin_id;
        }
        if($acc_name != ''){
            $map['acc_name'] = ['like','%'.$acc_name.'%'];
        }

        if($adv_id!=''){
            $map['adv_id'] = $adv_id;
        }

        // 查询条件end

        // 不是开发者或者超级管理员则只能看自己的数据
        $where_admin = [];
        if($this->uid != 1 && $this->group_id != 1){
            if($this->group_id ==7){
                $map['bind_youhua']=$this->uid;
            }else{
                $where_admin['id'] = $this->uid;
                $map['admin_id'] = $this->uid;
                if($youhua_name!=''){
                    $youhuaId=model('Admin')->alias('a')
                        ->join('auth_group_access b','a.id=b.uid')
                        ->where('realname',$youhua_name)->where('b.group_id',7)->value('a.id');
                    if($youhuaId){
                        $map['bind_youhua']=$youhuaId;
                    }else{
                        $map['bind_youhua']=0;
                    }
                }
            }
        }else{
            if($youhua_name!=''){
                $youhuaId=model('Admin')->alias('a')
                    ->join('auth_group_access b','a.id=b.uid')
                    ->where('realname',$youhua_name)->where('b.group_id',7)->value('a.id');
                if($youhuaId){
                    $map['bind_youhua']=$youhuaId;
                }else{
                    $map['bind_youhua']=0;
                }
            }
        }

        $infos = model('Account')->getInfosByMap($map, '', false);
        $channels = $this->getChannelArray();

        $industrys = model('Industry')->getListByMap();

        foreach ($infos as $k=>$v){
            $infos[$k]['clue_rate'] = floatval($v['clue_rate']);
            $infos[$k]['channel_name'] = $channels[$v['channel_id']];
            $infos[$k]['realname'] = $this->getAdminName($v['admin_id']);
            if($v['bind_youhua']){
                $infos[$k]['youhua_name'] = $this->getAdminName($v['bind_youhua']);
            }else{
                $infos[$k]['youhua_name']='';
            }
            $industry = Db::name('industry')->where('id','=',$v['hy_id'])->find();
            if($industry){
                $infos[$k]['hy_name'] = $industry['name'];
            }else{
                $infos[$k]['hy_name'] = '';
            }
        }

        $admins = model('Admin')->getListByMapAndOrder($where_admin, '', '',true,'id desc');

        $youhua = model('AuthGroupAccess')->alias('a')
            ->field('a.*,b.phone,b.realname')
            ->join('admin b','a.uid=b.id')
            ->where(function ($q){
                $q->where('a.group_id',7);
            })
//        ->where('a.group_id',4)
            ->where('b.delete_time',NULL)->select();

        return $this->fetch('',[
            'channel_id' => $channel_id,
            'acc_name' => $acc_name,
            'admin_id' => $admin_id,
            'infos' => $infos,
            'admins' => $admins,
            'industrys' => $industrys,
            'channels' => $channels,
            'youhua' => $youhua,
            'group_id' => $this->group_id,
            'adv_id' => $adv_id,
            'youhua_name' => $youhua_name,
        ]);
    }

    public function add()
    {
        if(request()->isAjax()){
            try{
                $save_data = input('post.');
                $save_data['admin_id'] = $this->uid;

                $save_data['adv_id'] = trim($save_data['adv_id']);
                $info = Db::name('account')->where('adv_id','=',$save_data['adv_id'])->find();
                if($info){
//                    if($save_data['channel']!=$info['channel_id']){
                        return $this->showReturnCode(1009,'账户ID已经存在');
//                    }
                    $id = $info['id'];
                }

                if(isset($id) && $id){
                    $save_data['id'] = $id;
                    $account_info = \db('account')->where('id', $id)->find();
                    if (empty($account_info)) {
                        return $this->showReturnCode(1009,'账户不存在');
                    }
                }

                if($save_data['channel']){
                    $save_data['channel_id']=$save_data['channel'];
                }

                if(empty($id)){
                    $save_data['app_key']=md5(uniqid().mt_rand(0,99999));
                }

                $result = $this->editData(false,'Account','Account',$save_data);
                if($result['code'] == 1001){
                    if(isset($id) && $id){

                        //编辑账号数据 修改分发规则表push中账号id，account_id
                        $channel_type1 = $account_info['channel_id']; //旧渠道
                        $channel_type2 = $save_data['channel_id']; //新渠道
                        $account_id = $id; //新增的账号id
                        $update = [];
                        if ($channel_type1 != $channel_type2) {
                            //旧渠道 移除账号
                            $push = \db('push')->where("find_in_set($channel_type1,channel_type)")->where('status', 1)->field('id,account_id')->select();
                            foreach ($push as $v) {
                                $account_ids = explode(",", $v['account_id']);
                                $key = array_search($account_id, $account_ids);// 查找值的键
                                unset($account_ids[$key]);
                                $account_id_str = implode(",", $account_ids);
                                $update[] = \db('push')->where('id', $v['id'])->fetchSql(true)->update(['account_id' => $account_id_str]);
                            }

                            //新渠道 添加账号
                            $push = \db('push')->where("find_in_set($channel_type2,channel_type)")->where('status', 1)->field('id,account_id')->select();
                            foreach ($push as $v) {
                                $account_ids = explode(",", $v['account_id']);
                                $key = array_search($account_id, $account_ids);// 查找值的键
                                unset($account_ids[$key]);
                                $account_id_str = implode(",", $account_ids);
                                $update[] = \db('push')->where('id', $v['id'])->fetchSql(true)->update(['account_id' => $account_id_str]);
                            }
                        }
                        if (!empty($update)) {
                            //执行批量操作
                            \db()->batchQuery($update);
                        }

                        $result['msg'] = '账户修改成功';
                        $this->RecordSystemLog($this->uid,$this->behavior,'账户【'.$save_data['acc_name'].'】修改成功');
                    }else{

                        //新增账号数据 给分发规则表push中的相同渠道增加账号id，account_id
                        $type = $save_data['channel_id']; //新增的渠道id
                        $account_id = \db('account')->getLastInsID(); //新增的账号id
                        $update = [];
                        $push = \db('push')->where("find_in_set($type,channel_type)")->where('status', 1)->field('id,account_id')->select();
                        foreach ($push as $v) {
                            $account_ids = $v['account_id']. ",".$account_id;
                            $update[] = \db('push')->where('id', $v['id'])->fetchSql(true)->update(['account_id' => $account_ids]);
                        }
                        if (!empty($update)) {
                            //执行批量操作
                            \db()->batchQuery($update);
                        }


                        $result['msg'] = '账户接入成功';
                        $this->RecordSystemLog($this->uid,$this->behavior,'账户【'.$save_data['acc_name'].'】接入成功');
                    }
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }

        $youhua = model('AuthGroupAccess')->alias('a')
            ->field('a.*,b.phone,b.realname')
            ->join('admin b','a.uid=b.id')
            ->where(function ($q){
                $q->where('a.group_id',7);
            })
//        ->where('a.group_id',4)
            ->where('b.delete_time',NULL)->select();
        return $this->fetch('',[
            'domain' => request()->domain(),
            'appid' => '1112019142',
            'youhua' => $youhua
        ]);
    }

    public function syn_status()
    {
        if($this->request->isAjax()){
            $id = input('post.id');
            $syn_status = input('post.status');

            $res = model('Account')->save(['syn_status'=>$syn_status],['id'=>$id]);
            if($res){
                if($syn_status == 1){
                    $account = model('Account')->find($id);
                    if($account['channel_id'] == 1){
                        (new BaiduService())->getReportData($id);
                    }elseif($account['channel_id'] == 2){
                        (new TengxunService())->getReportData($id);
                    }elseif($account['channel_id'] == 3){
                        (new JuliangService())->getReportData($id);
                    }else{
                        return $this->showReturnCode(1008,'渠道不支持数据同步');
                    }
                }
                $this->RecordSystemLog($this->uid,$this->behavior,'同步状态操作成功,操作账户ID: '.$id);
                return $this->showReturnCode(1001);
            }else{
                return $this->showReturnCode(1009,'操作失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }

    public function status()
    {
        if($this->request->isAjax()){
            $id = input('post.id');
            $res = model('Account')->save(['status'=>input('post.status')],['id'=>$id]);
            if($res){
                $this->RecordSystemLog($this->uid,$this->behavior,'状态操作成功,操作ID: '.$id);
                return $this->showReturnCode(1001);
            }else{
                return $this->showReturnCode(1009,'操作失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }

    public function edit()
    {
        $id = input('id');
        if(!$id) return self::showReturnCode(1002,'id 错误');
        $info = model('Account')->getInfoByMap(['id'=>$id]);
        return self::showJsonReturnCodeData('1001',$info,'');
    }

    public function save()
    {
        if(request()->isAjax()){
            try{

                $id = input('post.id');
                if(!$id){
                    return self::showReturnCode(1011,'id 错误');
                }
                $save_data = input('post.');

                if(isset($save_data['hy_id'])&&$save_data['hy_id'] == 0){
                    return self::showReturnCode(1011,'请选择关联行业');
                }

                $account_info = \db('account')->where('id', $id)->find();
                if (empty($account_info)) {
                    return $this->showReturnCode(1009,'账户不存在');
                }

                if (!empty($save_data['adv_id'])) {
                    $info = Db::name('account')->where('adv_id',$save_data['adv_id'])->where('id', "<>", $id)->find();
                    if($info){
                        return $this->showReturnCode(1009,'账户ID已经存在');
                    }
                    $save_data['adv_id'] = trim($save_data['adv_id']);
                }

                if (!empty($save_data['channel_id'])) {
                    //编辑账号数据 修改分发规则表push中账号id，account_id
                    $channel_type1 = $account_info['channel_id']; //旧渠道
                    $channel_type2 = $save_data['channel_id']; //新渠道
                    $account_id = $id; //新增的账号id
                    $update = [];
                    if ($channel_type1 != $channel_type2) {
                        //旧渠道 移除账号
                        $push = \db('push')->where("find_in_set($channel_type1,channel_type)")->where('status', 1)->field('id,account_id,channel_type')->select();
                        foreach ($push as $v) {
                            $channel_type = explode(",", $v['channel_type']);
                            //同时存在渠道则不处理
                            if ( in_array($channel_type1, $channel_type) && in_array($channel_type2, $channel_type)) {
                                continue;
                            }
                            $account_ids = explode(",", $v['account_id']);
                            $key = array_search($account_id, $account_ids);// 查找值的键
                            unset($account_ids[$key]);
                            $account_id_str = implode(",", $account_ids);
                            $update[] = \db('push')->where('id', $v['id'])->fetchSql(true)->update(['account_id' => $account_id_str]);
                        }

                        //新渠道 添加账号
                        $push = \db('push')->where("find_in_set($channel_type2,channel_type)")->where('status', 1)->field('id,account_id,channel_type')->select();
                        foreach ($push as $v) {
                            $account_ids = explode(",", $v['account_id']);
                            /*$channel_type = explode(",", $v['channel_type']);
                            //同时存在渠道则不处理
                            if ( in_array($channel_type1, $channel_type) && in_array($channel_type2, $channel_type)) {
                                continue;
                            }*/
                            if (!in_array($account_id, $account_ids)) {
                                $account_ids = $v['account_id']. ",".$account_id;
                                $update[] = \db('push')->where('id', $v['id'])->fetchSql(true)->update(['account_id' => $account_ids]);
                            }
                        }
                    }
                    \db()->batchQuery($update);
                }

                $result = $this->editData(false,'','Account',$save_data);
                if($result['code'] == 1001){
                    if(!empty($save_data['hy_id'])){
                        $result['msg'] = '关联行业成功';
                        $this->RecordSystemLog($this->uid,$this->behavior,'广告账户【'.$id.'】关联行业成功');
                    }else{
                        $result['msg'] = '修改成功';
                        $this->RecordSystemLog($this->uid,$this->behavior,'广告账户【'.$id.'】修改成功');
                    }
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    public function copy()
    {
        if(request()->isAjax()){
            try{
                $id = input('copy_id');

                $account_info = \db('account')->where('id', $id)->find();
                if (empty($account_info)) {
                    return $this->showReturnCode(1009,'复制的账户不存在');
                }

                $save_data = input('post.');

                $save_data['hy_id'] = $account_info['hy_id'];
                $save_data['status'] = $account_info['status'];
                $save_data['admin_id'] = $account_info['admin_id'];

                if (!empty($save_data['adv_id'])) {
                    $info = Db::name('account')->where('adv_id',$save_data['adv_id']) ->find();
                    if($info){
                        return $this->showReturnCode(1009,'账户ID已经存在');
                    }
                    $save_data['adv_id'] = trim($save_data['adv_id']);
                }

                $result = $this->editData(false,'','Account',$save_data);

                if (!empty($save_data['channel_id'])) {
                    //新增账号数据 给分发规则表push中的相同渠道增加账号id，account_id
                    $type = $save_data['channel_id']; //新增的渠道id
                    $account_id = \db('account')->getLastInsID(); //新增的账号id
                    $update = [];
                    $push = \db('push')->where("find_in_set($type,channel_type)")->where('status', 1)->field('id,account_id')->select();
                    foreach ($push as $v) {
                        $account_ids = $v['account_id']. ",".$account_id;
                        $update[] = \db('push')->where('id', $v['id'])->fetchSql(true)->update(['account_id' => $account_ids]);
                    }
                    if (!empty($update)) {
                        //执行批量操作
                        \db()->batchQuery($update);
                    }
                }

                if($result['code'] == 1001){
                    $result['msg'] = '添加成功';
                    $this->RecordSystemLog($this->uid,$this->behavior,'广告账户【'.$save_data['adv_id'].'】修改成功');
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }


    public function cityStop()
    {
        $acc_name = input('acc_name','');
        $status = input('status','');
        $cityname = input('cityname','');

        $map = [];

        //模糊查询城市
        if(!empty($cityname)){
            $cityIdArr=Db::name('city')->field('id,type,pid')->where('name','like',$cityname."%")->where('type',2)->find();
            if($cityIdArr){
                $map['a.city']=$cityIdArr['pid'].'-'.$cityIdArr['id'];
            }else{
                $map['a.city']=0;
            }
        }

        if($acc_name!=''){
            $accId=model('Account')->where('like','%'.$acc_name.'%')->column('id');
            $map['acc_id']=['in',$accId];
        }

        if($status!=''){
            $map['status']=$status;
        }
        $accountAll=Db::name('Account')->column('acc_name','id');

//        $infos = model('Push')->getInfosByMap($map, '', false);
        $infos = model('AccountCity')->alias('a')
            ->where($map)
            ->order('id desc')->paginate();
        foreach ($infos as $k=>$v){
            $infos[$k]['acc_name']=$accountAll[$v['acc_id']];

            if($v['city'] != ''){
                $ids = explode('-',$v['city']);
                $prov = $this->getCityName($ids[0]);
                $city = $this->getCityName($ids[1]);
                if($prov == $city){
                    $infos[$k]['city'] = $prov;
                }else{
                    $infos[$k]['city'] = $prov.'-'.$city;
                }
            }

        }

        $province = Db::name('city')->where(['pid'=>1])->select();



        $account=model('Account')->getListByMap([],'id,acc_name,adv_id,channel_id');

        $accountList=[];
        foreach ($account as $v){
            $accountList[]=['value'=>$v['id'],'name'=>$v['acc_name']];
        }
        $accountList=json_encode($accountList,JSON_UNESCAPED_UNICODE);


        return $this->fetch('',[
            'infos' => $infos,
            'acc_name' => $acc_name,
            'status' => $status,
            'province' => $province,
            'group_id' => $this->group_id,
            'cityname' => $cityname,
            'account' => $accountList,
            'status' => $status,
        ]);
    }

    public function citySave()
    {
        if (request()->isAjax()) {
            try {

                $id = input('post.id');
                $save_data = input('post.');

                if (empty($save_data['acc_id'])) {
                    return self::showReturnCode(1011, '请选择账户');
                }

                if (empty($save_data['city'])) {
                    return self::showReturnCode(1011, '请选择城市');
                }

                $city=Db::name('city')->where('id',$save_data['city'])->find();
                $saveCity=$city['pid'].'-'.$city['id'];

                $adminArr = explode(',', $save_data['acc_id']);
                $insertData = [];
                foreach ($adminArr as $v) {
                    $insertData[] = ['acc_id' => $v, 'city' => $saveCity];
                }

                $result = model('AccountCity')->saveAll($insertData);
                $this->RecordSystemLog($this->uid, $this->behavior, '城市保存成功');

                return self::showReturnCode(1001, '保存成功');
            } catch (\Exception $e) {
                Log::error($e->getMessage());
                return self::showReturnCode(1011, $e->getMessage());
            }
        } else {
            return self::showReturnCode(1002);
        }
    }

    public function cityStatus()
    {
        if($this->request->isAjax()){
            $id = input('post.id');
            $res = model('AccountCity')->save(['status'=>input('post.status')],['id'=>$id]);
            if($res){
                $this->RecordSystemLog($this->uid,$this->behavior,'状态操作成功,操作ID: '.$id);
                return $this->showReturnCode(1001);
            }else{
                return $this->showReturnCode(1009,'操作失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }

    public function cityEdit()
    {
        $id = input('id');
        if(!$id) return self::showReturnCode(1002,'id 错误');
        $info = model('AccountCity')->getInfoByMap(['id'=>$id]);
        if($info['city'] != 0){
            $ids = explode('-',$info['city']);
            $info['prov'] = $ids[0];
            $info['city'] = $ids[1];
            $info['city_name'] = $this->getCityName($ids[1]);
        }else{
            $info['prov'] = 0;
            $info['city'] = 0;
            $info['city_name'] = '';
        }
        return self::showJsonReturnCodeData('1001',$info,'');
    }

    /**
     * 软删除
     */
    public function cityDelete()
    {
        if($this->request->isAjax()){
            $id = input('post.id');

            $res = model('AccountCity')->destroy($id);
            if($res){
                $this->RecordSystemLog($this->uid,$this->behavior,'删除成功,操作ID: '.$id);
                return $this->showReturnCode(1001,'删除成功');
            }else{
                return $this->showReturnCode(1009,'删除失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }
}